package com.wy.web.interceptor;


import com.alibaba.fastjson.JSON;
import com.wy.common.exception.BizException;
import com.wy.dto.war.UserAccountDto;
import com.wy.protocol.ERRORCODE;
import com.wy.service.ex.IUserAccountExService;
import com.wy.util.RedisUtil;
import com.wy.web.constant.WebRedisConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOGGER= LoggerFactory.getLogger(AuthInterceptor.class);

	public AuthInterceptor() { }

	@Autowired
	private IUserAccountExService userAccountExService;

    @Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		String url = request.getServletPath();
		if("/index.html".equals(url)){
			return true;
		}
//		System.out.println("===========HandlerInterceptor1 preHandle");

		String token = request.getParameter("token");

		if (StringUtils.isEmpty(token)) {
			throw new BizException(ERRORCODE.PARAM_ERROR.getCode(), ERRORCODE.PARAM_ERROR.getMessage());
//			request.getRequestDispatcher().forward(request, response);
//			response.sendRedirect("/doLogin.do");
		}

		String key = WebRedisConst.USER_KEY+token;

		RedisUtil.getInstance().del(key);

		if(!RedisUtil.getInstance().exists(key)) {

			UserAccountDto userAccountDto = userAccountExService.findUserAccountDtoByToken(token);

			RedisUtil.getInstance().set(key, JSON.toJSONString(userAccountDto),1, TimeUnit.HOURS);

		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
//		System.out.println("===========HandlerInterceptor1 postHandle");

	}

	@Override
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//		System.out.println("===========HandlerInterceptor1 afterCompletion");
	}

}
